package cst.a729yt.zyfypt_729yt.Activity;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import cst.a729yt.zyfypt_729yt.Bean.LoginBean;
import cst.a729yt.zyfypt_729yt.R;
import cst.a729yt.zyfypt_729yt.ResModel;
import cst.a729yt.zyfypt_729yt.ytListener;


public class LoginActivity extends AppCompatActivity {
    private EditText username;
    private EditText password;
    private Button btn_login;
    private Button btn_reg;
    private ResModel model;
    private ytListener<LoginBean> listener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        username = (EditText) findViewById(R.id.login_username);
        password = (EditText) findViewById(R.id.login_password);
        btn_login = (Button) findViewById(R.id.btn_login);
        btn_reg = (Button) findViewById(R.id.btn_reg);
        listener = new ytListener<LoginBean>() {
            @Override
            public void onResponse(LoginBean l) {
                if (l.getUsername() != null) {
                    String sessionid = l.getSessionid();
                    //把sessionid存到一个地方
                    Intent intent = new Intent(
                            LoginActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    Toast.makeText(LoginActivity.this, "用户名或密码错误",
                            Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFail(String msg) {
                Toast.makeText(LoginActivity.this, msg,
                        Toast.LENGTH_SHORT).show();
            }
        };

        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                model = new ResModel("gson");
                model.login(username.getText().toString(),
                        password.getText().toString(),
                        listener);
            }
        });
        btn_reg.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(
                        LoginActivity.this, RegActivity.class
                );
                startActivity(intent);
                finish();
            }
        });

    }

}
